/*
 * launcherDialog.java
 *
 * Created on 30.11.2010, 7:33:05
 */

package gen_seq.ui;

import gen_seq.generator.*;
import java.io.IOException;
import java.util.logging.*;
import java.util.zip.*;
import javax.swing.*;

/**
 *
 * @author akademi4eg
 */
public class launcherDialog extends JDialog {

    /** Creates new form launcherDialog */
    public launcherDialog(GenFrame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(btnLaunch);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtPopLen = new javax.swing.JFormattedTextField();
        txtChrLen = new javax.swing.JFormattedTextField();
        btnCancel = new javax.swing.JButton();
        btnLaunch = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        txtCorr = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtCorrsNum = new javax.swing.JFormattedTextField();
        jLabel5 = new javax.swing.JLabel();
        cmbGenesType = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Generation parameters");
        setModal(true);
        setName("launcherDg"); // NOI18N
        setResizable(false);

        jLabel1.setText("Population size:");
        jLabel1.setToolTipText("Number of elements in population.");

        jLabel2.setText("Chromosome length:");

        txtPopLen.setColumns(3);
        txtPopLen.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        txtPopLen.setText("5");
        txtPopLen.setToolTipText("Number of elements in population.");

        txtChrLen.setColumns(8);
        txtChrLen.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        txtChrLen.setText("1000");
        txtChrLen.setToolTipText("Number og genes in chromosome");

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        btnLaunch.setText("Launch");
        btnLaunch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLaunchActionPerformed(evt);
            }
        });

        jLabel3.setText("Correlator C(r)=");

        txtCorr.setText("exp(-r)");
        txtCorr.setToolTipText("Enter correlator here.");

        jLabel4.setText("Control points num:");

        txtCorrsNum.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        txtCorrsNum.setText("10");

        jLabel5.setText("Genes type:");

        cmbGenesType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Binary {0, 1}", "Ternary {0, 1, 2}" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel3))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jLabel1))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel2))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(jLabel5))
                                .addGroup(layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(jLabel4))
                                .addGroup(layout.createSequentialGroup()
                                    .addContainerGap(81, Short.MAX_VALUE)
                                    .addComponent(btnLaunch))))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtChrLen, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addComponent(btnCancel)
                    .addComponent(txtPopLen, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addComponent(txtCorr, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addComponent(txtCorrsNum, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                    .addComponent(cmbGenesType, 0, 138, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPopLen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtChrLen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCorr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCorrsNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(cmbGenesType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLaunch)
                    .addComponent(btnCancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnLaunchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLaunchActionPerformed
        if (Integer.parseInt(txtPopLen.getText()) <= 0)
        {
            JOptionPane.showMessageDialog(this, "Population size must be positive!", "Validation error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (Integer.parseInt(txtChrLen.getText()) <= 0)
        {
            JOptionPane.showMessageDialog(this, "Chromosome length must be positive!", "Validation error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (Integer.parseInt(txtCorrsNum.getText()) <= 0)
        {
            JOptionPane.showMessageDialog(this, "Number of correlator points to count must be positive!", "Validation error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            EtalonCorrelator.setExpression(txtCorr.getText());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Error while parsing expression for correlator. "+ex.getMessage(), "Validation error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        ((GenFrame)getParent()).lockElementsDueToLaunch();
        // starting population
        new Thread(new Runnable() {
            public void run() {
                try {
                    switch (cmbGenesType.getSelectedIndex()) {
                        case 0:
                            Population.getInstance().setGenesType(GeneTypes.BINARY);
                            break;
                        case 1:
                            Population.getInstance().setGenesType(GeneTypes.TERNARY);
                            break;
                        default:
                            throw new IllegalArgumentException("Unknown gene type selected.");
                    }
                    Population.getInstance().setLength(Integer.parseInt(txtPopLen.getText()));
                    Population.getInstance().setChromosomeLength(Integer.parseInt(txtChrLen.getText()));
                    StatsCollector.CORR_LEN = Integer.parseInt(txtCorrsNum.getText());
                    Population.getInstance().init();

                    ((GenFrame) getParent()).updateStats(StatsCollector.POPULATION_LENGTH, Integer.toString(Population.getInstance().getLength()));
                    ((GenFrame) getParent()).updateStats(StatsCollector.CHROMOSOME_LENGTH, Integer.toString(Population.getInstance().getChromosomeLength()));
                    ((GenFrame) getParent()).initStatsTable(Population.getInstance().getLength());
                    
                    Population.getInstance().setActive(true);
                    Population.getInstance().setRunning(true);

                    Chromosome filler;
                    while (Population.getInstance().isRunning())
                    {
                        if (!Population.getInstance().isActive()) continue;
                        try {
                            Population.getInstance().getEvolutionKeeper().acquire();
                            Population.getInstance().evolve();
                            filler = Population.getInstance().getBest();
                            if (Population.keep_best && Population.getInstance().getBestAchievement().getFitness() < filler.getFitness())
                                filler = Population.getInstance().getBestAchievement();
                            Population.getInstance().fill(filler);
                            Population.getInstance().getEvolutionKeeper().release();
                        } catch (InterruptedException ex) {
                            Logger.getLogger(launcherDialog.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    ((GenFrame)getParent()).unlockElementsDueToLaunch();
                } catch (DataFormatException ex) {
                    Logger.getLogger(launcherDialog.class.getName()).log(Level.SEVERE, null, ex);
                    ((GenFrame)getParent()).unlockElementsDueToLaunch();
                }
            }
        }).start();

        // starting stats collector
        new java.util.Timer().schedule(new StatsCollector((GenFrame) getParent()), StatsCollector.DELAY, StatsCollector.DELAY);
                    
        dispose();
    }//GEN-LAST:event_btnLaunchActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnLaunch;
    private javax.swing.JComboBox cmbGenesType;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JFormattedTextField txtChrLen;
    private javax.swing.JTextField txtCorr;
    private javax.swing.JFormattedTextField txtCorrsNum;
    private javax.swing.JFormattedTextField txtPopLen;
    // End of variables declaration//GEN-END:variables

}
